package com.nest.WorkNest.act;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.bigkoo.pickerview.OptionsPopupWindow;
import com.lidroid.xutils.exception.HttpException;
import com.nest.WorkNest.R;
import com.nest.WorkNest.api.XutilsPost;
import com.nest.WorkNest.entity.AddressInfo;
import com.nest.WorkNest.tools.Tool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
public class AddAddressAct extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.edtTxt_addaddress_name)
    EditText edtTxtAddaddressName;
    @Bind(R.id.edtTxt_addaddress_phone)
    EditText edtTxtAddaddressPhone;
    @Bind(R.id.edtTxt_addaddress_address)
    EditText edtTxtAddaddressAddress;
    @Bind(R.id.btn_addaddress_compelete)
    Button btnAddaddressCompelete;
    @Bind(R.id.edtTxt_addaddress_pcd)
    EditText edtTxtAddaddressPcd;
    @Bind(R.id.edtTxt_addaddress_zip)
    EditText edtTxtAddaddressZip;
    //    @Bind(R.id.edtTxt_addaddress_sheng)
//    EditText edtTxtAddaddressSheng;
//    @Bind(R.id.edtTxt_addaddress_city)
//    EditText edtTxtAddaddressCity;
    private AddressInfo addressInfo;
    private String name, cellPhone, address, province, city, zip;
    private Context context = AddAddressAct.this;
    private ArrayList<String> options1Items = new ArrayList<String>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<ArrayList<String>>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<ArrayList<ArrayList<String>>>();
    private OptionsPopupWindow pwOptions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_addaddress);
        ButterKnife.bind(this);
        initPicker();
        initView();

    }

    public void initView() {
        initBar();
        initProgress(context, "提交中...");
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        actionbar_side_name.setVisibility(View.VISIBLE);
        actionbar_side_name.setText("新建收货地址");
        ll_iv_actionbar_side_left.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(getIntent().getStringExtra("addressId"))) {
            tv_actionbar_side_right.setText("删除");
            ll_tv_actionbar_side_right.setVisibility(View.VISIBLE);
            edtTxtAddaddressAddress.setText(getIntent().getStringExtra("address"));
            edtTxtAddaddressPhone.setText(getIntent().getStringExtra("cellPhone"));
            edtTxtAddaddressName.setText(getIntent().getStringExtra("name"));
            edtTxtAddaddressPcd.setText(getIntent().getStringExtra("province") + getIntent().getStringExtra("city"));
            edtTxtAddaddressZip.setText(getIntent().getStringExtra("postCard"));
        }
        back();
        addressInfo = new AddressInfo();
        edtTxtAddaddressAddress.clearFocus();
        edtTxtAddaddressPhone.clearFocus();
        edtTxtAddaddressName.clearFocus();
        btnAddaddressCompelete.setOnClickListener(this);
        ll_tv_actionbar_side_right.setOnClickListener(this);
        edtTxtAddaddressPcd.setOnClickListener(this);
    }


    public void loadAddaddress() {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                if (Tool.getString(result, "resultCode").equals("0")) {
                    finish();
                } else if (Tool.getString(result, "resultCode").equals("9101") || Tool.getString(result, "resultCode").equals("9002")) {
                    showToast(Tool.getString(result, "MSG"));
                    if (pd.isShowing()) {
                        pd.cancel();
                    }
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {
                if (pd.isShowing()) {
                    pd.cancel();
                }
            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {
                if (!pd.isShowing()) {
                    pd.show();
                }
            }
        };
        xutilsPost.doPostAddaddress(context, addressInfo, ioAuthCallBack);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_addaddress_compelete:
                name = edtTxtAddaddressName.getText().toString();
                cellPhone = edtTxtAddaddressPhone.getText().toString();
                address = edtTxtAddaddressAddress.getText().toString();
                zip = edtTxtAddaddressZip.getText().toString();
//                province = edtTxtAddaddressSheng.getText().toString();
//                city = edtTxtAddaddressCity.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    showToast("请填写收件人姓名");
                } else if (TextUtils.isEmpty(cellPhone)) {
                    showToast("请填写收件人电话");
                } else if (TextUtils.isEmpty(address)) {
                    showToast("请填写详细收货地址");
                } else if (TextUtils.isEmpty(zip)) {
                    showToast("请填写邮政编码");
                } else if (TextUtils.isEmpty(province)) {
                    showToast("请填写省份");
                } else if (TextUtils.isEmpty(city)) {
                    showToast("请填写城市");
                } else {
                    addressInfo.setName(name);
                    addressInfo.setCellPhone(cellPhone);
                    addressInfo.setAddress(address);
                    addressInfo.setProvince(province);
                    addressInfo.setCity(city);
                    if (getIntent().getStringExtra("addressId") == null) {
                        addressInfo.setAddressId("0");
                        addressInfo.setType("0");
                    } else if (getIntent().getStringExtra("addressId") == null) {
                        addressInfo.setAddressId(getIntent().getStringExtra("addressId"));
                        addressInfo.setType(getIntent().getStringExtra("addressId"));
                    }
                    loadAddaddress();
                }
                break;
            case R.id.ll_tv_actionbar_side_right:
                name = edtTxtAddaddressName.getText().toString();
                cellPhone = edtTxtAddaddressPhone.getText().toString();
                address = edtTxtAddaddressAddress.getText().toString();
                addressInfo.setType("1");
                addressInfo.setPostCard(zip);
                addressInfo.setAddressId(getIntent().getStringExtra("addressId"));
                addressInfo.setName(name);
                addressInfo.setCellPhone(cellPhone);
                addressInfo.setAddress(address);
                loadAddaddress();
                break;
            case R.id.edtTxt_addaddress_pcd:
                pwOptions.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;
        }
    }

    public void initPicker() {
        pwOptions = new OptionsPopupWindow(this);
        AssetManager s = context.getResources().getAssets();
        //省份注入
        try {
            InputStream is = s.open("province.json");
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            String json = new String(buffer, "utf-8");
            is.close();
            JSONArray province;
            JSONObject jsonObject;
            try {
                province = new JSONArray(json);
                for (int i = 0; i < province.length(); i++) {
                    jsonObject = province.getJSONObject(i);
                    String name = jsonObject.getString("name");
                    options1Items.add(name);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        //选项选择器
        try {
            InputStream is = s.open("city.json");
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            String json = new String(buffer, "utf-8");
            is.close();
            JSONArray city;
            JSONObject jsonObject;
            try {
                city = new JSONArray(json);

                for (int j = 1; j < 35; j++) {
                    ArrayList<String> cityArray = new ArrayList<>();
                    for (int i = 0; i < city.length(); i++) {
                        jsonObject = city.getJSONObject(i);
                        if (jsonObject.getString("ProID").equals(j + "")) {
                            String name = jsonObject.getString("name");
                            cityArray.add(name);
                        }
                    }
                    options2Items.add(cityArray);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        pwOptions.setPicker(options1Items, options2Items, true);
        pwOptions.setSelectOptions(0, 0);
        //监听确定选择按钮
        pwOptions.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1)
                        + options2Items.get(options1).get(option2);
                province = options1Items.get(options1);
                city = options2Items.get(options1).get(option2);
                edtTxtAddaddressPcd.setText(tx);
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        try {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                    manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.onTouchEvent(event);
    }
}
